package com.example.concurrentprogramming8016.reetrantlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author liyanhao
 * @Date 2023-01-05 19:07
 * 获取锁超时失败
 */
@Slf4j
public class ReentrantLockDemo5 {
    public static void main(String[] args) throws InterruptedException {
        ReentrantLock reentrantLock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            log.debug("t1 启动了");
            //超时
            try {
                if (!reentrantLock.tryLock(3, TimeUnit.SECONDS)) {
                    log.debug("等待1秒后获取锁失败,返回");
                    return;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            reentrantLock.lock();
            try {
                log.debug("t1获得了锁");
            } finally {
                reentrantLock.unlock();
            }
        });
        reentrantLock.lock();
        log.debug("main线程获得了锁");
        t1.start();
        //先让线程t1执行 调节超时时间可以获得锁
        TimeUnit.SECONDS.sleep(2);
        reentrantLock.unlock();
    }
}
